package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.CartMapper;
import com.example.model.dto.CartDTO;
import com.example.model.dto.Result;
import com.example.model.dto.UpdateCartDTO;
import com.example.model.entity.Cart;
import com.example.model.entity.Shop;
import com.example.model.vo.CartVO;
import com.example.model.vo.CartsVO;
import com.example.model.vo.ShopDetailVO;
import com.example.model.vo.UserVO;
import com.example.service.ICartService;
import com.example.service.IShopService;
import com.example.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: backend
 * @author: zk
 * @create: 2023-04-22 13:43
 **/
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    @Resource
    private IShopService shopService;

    @Resource
    private IUserService userService;

    @Resource
    private CartMapper cartMapper;

    @Override
    public Result getCarts(HttpServletRequest request) {

        // 1.获取登录用户信息
        UserVO user = userService.getLoginUser(request);


        // 3.获取session中用户id
        String userId = user.getId();

        // 4.查询用户的购物车信息
        List<Cart> carts = query().eq("userId", userId).list();

        List<CartVO> cartVOs = new ArrayList<CartVO>();
        double cartTotalPrice = 0;
        boolean isSelected = true;
        for (Cart cart : carts) {
            CartVO cartVO = new CartVO();

            cartVO.setId(cart.getId());
            cartVO.setUserId(cart.getUserId());
            cartVO.setProductId(cart.getProductId());
            cartVO.setQuantity(cart.getQuantity());
            cartVO.setProductStatus(cart.getProductStatus());
            cartVO.setProductSelected(cart.getProductSelected() == 1);

            // 根据产品id查询产品详细信息
            Shop shop = shopService.getShopsById(cart.getProductId());

            cartVO.setProductName(shop.getName());
            cartVO.setProductSubtitle(shop.getSubtitle());
            cartVO.setProductMainImage(shop.getMainImage());
            cartVO.setProductPrice(shop.getPrice());

            // 计算购物车中的某件商品的总金额
            double sum = 0;
            sum = shop.getPrice() * cart.getQuantity();
            // 判断该购物车中商品是否选中
            if (cart.getProductSelected() == 0) {   // 未选中
                isSelected = false;
            } else {    // 选中，商品为选中状态 为 cartTotalPrice 添加金额
                cartTotalPrice += sum;
            }
            cartVO.setProductTotalPrice(sum);

            // 向返回信息中添加已封装信息
            cartVOs.add(cartVO);

        }

        // 5.封装前端数据
        CartsVO cartsVO = new CartsVO();
        cartsVO.setCartProductVoList(cartVOs);
        cartsVO.setCartTotalPrice(cartTotalPrice);
        cartsVO.setSelectedAll(isSelected);

        return Result.ok(cartsVO);
    }

    @Override
    public Result addCart(CartDTO cartDTO,HttpServletRequest request) {

        // 2.获取登录用户
        UserVO user = userService.getLoginUser(request);


        // 3.判断该用户购物车是否已经拥有该产品
        Cart cart = query()
                .eq("userId", user.getId())
                .eq("productId", cartDTO.getProductId())
                .one();

        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        // 4.购物车存在该产品
        if (cart != null) {

            // 4.1 从购物车中删除此商品
            if (cart.getQuantity() + cartDTO.getQuantity() == 0) {
                return deleteCart(cartDTO.getProductId(),request);
            } else {    // 4.2更新购物车中信息
                updateWrapper
                        .eq("userId", user.getId())
                        .eq("productId", cartDTO.getProductId())
                        .set("quantity", cart.getQuantity() + cartDTO.getQuantity())
                        .set("productSelected", cartDTO.isSelected() ? 1 : 0);
                int i = cartMapper.update(cart, updateWrapper);
                if (i == 1) {
                    return this.getCarts(request);
                }else{
                    return Result.fail("更新失败");
                }
            }
        }

        // 5.不存在该产品
        cart = new Cart();

        cart.setUserId(user.getId());
        cart.setProductId(cartDTO.getProductId());
        cart.setProductSelected(cartDTO.isSelected() ? 1 : 0);
        cart.setQuantity(1);
        cart.setProductStatus(1);
        ShopDetailVO shop = (ShopDetailVO) shopService.getShop(cartDTO.getProductId() + "").getData();
        cart.setPrice(shop.getPrice());


        // 6.添加购物信息到数据库中
        boolean save = save(cart);

        if (!save) {
            return Result.fail("服务器繁忙");
        }

        return this.getCarts(request);
    }

    @Override
    public Result updateCart(UpdateCartDTO updateCartDTO,HttpServletRequest request) {

        // 1.获取用户信息
        UserVO user = userService.getLoginUser(request);

        // 2.查询要更新购物车产品信息
        Cart cart = query()
                .eq("userId", user.getId())
                .eq("productId", updateCartDTO.getProductId())
                .one();

        // 3.设置更新条件
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("userId", user.getId())
                .eq("productId", updateCartDTO.getProductId())
                .set("quantity", + updateCartDTO.getQuantity());

        // 4.更新
        int i = cartMapper.update(cart, updateWrapper);
        if (i == 1) {
            // 成功
            return this.getCarts(request);
        }else{
            // 失败
            return Result.fail("更新失败");
        }
    }

    @Override
    public Result deleteCart(Long productId,HttpServletRequest request) {

        // 1.获取登录用户信息
        UserVO user = userService.getLoginUser(request);
        // 2.查询要指定购物车中要删除的id
        Cart cart = query()
                .eq("userId", user.getId())
                .eq("productId", productId)
                .one();

        if(cart == null) {
            return Result.fail("输入信息有误（购物车中没有该商品）");
        }

        int id = cart.getId();

        // 3.删除
        int i = cartMapper.deleteById(id);

        // 4.判断是否删除成功
        if (i == 0) {
            // 失败
            return Result.fail("删除失败，服务器异常");
        }

        // 5.返回信息
        return this.getCarts(request);
    }

    @Override
    public Result selectAll(HttpServletRequest request) {
        UserVO user = userService.getLoginUser(request);

        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("userId", user.getId())
                .set("productSelected", 1);
        int update = cartMapper.update(null, updateWrapper);
        if (update == 0) {
            return Result.fail("更新失败，服务器繁忙");
        }
        return Result.ok();
    }

    @Override
    public Result unSelectAll(HttpServletRequest request) {
        UserVO user = userService.getLoginUser(request);

        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("userId", user.getId())
                .set("productSelected", 0);
        int update = cartMapper.update(null, updateWrapper);
        if (update == 0) {
            return Result.fail("更新失败，服务器繁忙");
        }
        return Result.ok();
    }

    @Override
    public Result getProductCount(HttpServletRequest request) {
        // 获取当前登录用户信息
        UserVO user = userService.getLoginUser(request);

        // 查询
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("quantity").eq("userId", user.getId());
        List<Cart> list = cartMapper.selectList(queryWrapper);

        // 取值
        int sum = 0;
        for (Cart cart : list) {
            sum += cart.getQuantity();
        }

        // 返回
        return Result.ok(sum);
    }


}
